package ca.ericslandry.server.handler;

import java.util.ArrayList;
import java.util.List;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;
import ca.ericslandry.server.dao.IssueDAO;
import ca.ericslandry.server.dao.ShardedCounter;
import ca.ericslandry.shared.domain.Issue;
import ca.ericslandry.shared.rpc.GetIssues;
import ca.ericslandry.shared.rpc.GetIssuesResult;

public class GetIssuesHandler implements ActionHandler<GetIssues, GetIssuesResult> {
	@Override
	public GetIssuesResult execute(GetIssues action, ExecutionContext context) throws ActionException {
		List<Issue> retVal = new ArrayList<Issue>();
		IssueDAO dao = new IssueDAO();
		List<Issue> issues = dao.listAllForPage(action.getStartRow(), action.getNumRows(), "-creationDate");
		for (Issue issue : issues) {
			ShardedCounter counter = new ShardedCounter(issue.toString());
			issue.setViewCount(counter.getCount());
			retVal.add(issue);
		}
		return new GetIssuesResult(retVal);
	}

	@Override
	public Class<GetIssues> getActionType() {
		return GetIssues.class;
	}

	@Override
	public void rollback(GetIssues action, GetIssuesResult result, ExecutionContext context) throws ActionException {
		// Nothing to do here
	}
}
